const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 创建订单
  async createOrder(orderData) {
    try {
      // 验证格子是否可用
      const cellRes = await db.collection('locker_cell')
        .doc(orderData.cell_id)
        .field({
          status: true
        })
        .get()
      
      if (!cellRes.data || cellRes.data.length === 0) {
        return {
          code: 404,
          message: '寄存格不存在'
        }
      }
      
      const cell = cellRes.data[0]
      if (cell.status !== 0) {
        return {
          code: 400,
          message: '该寄存格已被占用'
        }
      }
      
      // 计算价格
      const price = await this.calculatePrice(
        orderData.depot_id,
        orderData.size_type,
        orderData.start_time,
        orderData.end_time,
        orderData.insurance
      )
      
      // 生成订单数据
      const order = {
        user_id: orderData.user_id,
        depot_id: orderData.depot_id,
        cell_id: orderData.cell_id,
        size_type: orderData.size_type,
        start_time: new Date(orderData.start_time),
        end_time: new Date(orderData.end_time),
        total_price: price,
        status: 'unpaid',
        payment_status: 0,
        insurance: orderData.insurance,
        create_time: new Date()
      }
      
      // 开启事务
      const transaction = await db.startTransaction()
      
      // 1. 创建订单
      const orderRes = await transaction.collection('order').add(order)
      
      // 2. 更新格子状态
      await transaction.collection('locker_cell').doc(orderData.cell_id).update({
        status: 1 // 占用状态
      })
      
      // 提交事务
      await transaction.commit()
      
      return {
        code: 0,
        message: '订单创建成功',
        data: {
          order_id: orderRes.id
        }
      }
    } catch (e) {
      console.error('创建订单失败:', e)
      return {
        code: 500,
        message: '创建订单失败',
        data: null
      }
    }
  },
  
  // 计算价格
  async calculatePrice(depotId, sizeType, startTime, endTime, insurance) {
    // 获取小时单价
    const depotObj = uniCloud.importObject('depot')
    const priceRes = await depotObj.getPriceBySize(depotId, sizeType)
    const hourPrice = priceRes
    
    // 计算小时数
    const start = new Date(startTime)
    const end = new Date(endTime)
    const hours = Math.ceil((end - start) / (1000 * 60 * 60))
    
    let price = hourPrice * hours
    
    // 保险费用
    if (insurance && insurance.enabled) {
      price += 5
    }
    
    return price
  },
  
  // 获取用户订单列表
  async getOrderList(userId, status, page = 1, pageSize = 10) {
    try {
      // 构建查询条件
      const where = {
        user_id: userId
      }
      
      if (status && status !== 'all') {
        where.status = status
      }
      
      // 获取订单数据
      const orderRes = await db.collection('order')
        .where(where)
        .field({
          _id: true,
          depot_id: true,
          cell_id: true,
          size_type: true,
          start_time: true,
          end_time: true,
          total_price: true,
          status: true,
          payment_status: true,
          create_time: true
        })
        .orderBy('create_time', 'desc')
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .get()
      
      // 获取关联的站点信息
      const depotIds = [...new Set(orderRes.data.map(order => order.depot_id))]
      const depotRes = await db.collection('depot')
        .where({
          _id: dbCmd.in(depotIds)
        })
        .field({
          _id: true,
          name: true,
          address: true,
          images: true
        })
        .get()
      
      const depotMap = {}
      depotRes.data.forEach(depot => {
        depotMap[depot._id] = depot
      })
      
      // 组合数据
      const orders = orderRes.data.map(order => {
        const depot = depotMap[order.depot_id] || {}
        return {
          id: order._id,
          orderId: order._id.substring(0, 8).toUpperCase(),
          status: order.status,
          depotName: depot.name || '未知站点',
          address: depot.address || '',
          image: depot.images && depot.images.length > 0 ? depot.images[0] : '',
          type: this.getSizeName(order.size_type),
          startTime: this.formatDate(order.start_time),
          endTime: this.formatDate(order.end_time),
          price: order.total_price,
          createTime: this.formatDate(order.create_time, 'YYYY-MM-DD HH:mm')
        }
      })
      
      return {
        code: 0,
        message: '获取订单成功',
        data: orders
      }
    } catch (e) {
      console.error('获取订单失败:', e)
      return {
        code: 500,
        message: '获取订单失败',
        data: null
      }
    }
  },
  
  // 格式化日期
  formatDate(date, format = 'YYYY-MM-DD') {
    if (!date) return ''
    const d = new Date(date)
    const year = d.getFullYear()
    const month = (d.getMonth() + 1).toString().padStart(2, '0')
    const day = d.getDate().toString().padStart(2, '0')
    
    if (format === 'YYYY-MM-DD') {
      return `${year}-${month}-${day}`
    } else {
      const hours = d.getHours().toString().padStart(2, '0')
      const minutes = d.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
  },
  
  // 根据尺寸类型获取名称
  getSizeName(sizeType) {
    const sizeMap = {
      0: '小箱型',
      1: '中箱型',
      2: '大箱型'
    }
    return sizeMap[sizeType] || '未知箱型'
  },
  
  // 获取订单详情
  async getOrderDetail(orderId) {
    try {
      // 获取订单基本信息
      const orderRes = await db.collection('order')
        .doc(orderId)
        .field({
          _id: true,
          user_id: true,
          depot_id: true,
          cell_id: true,
          size_type: true,
          start_time: true,
          end_time: true,
          actual_end_time: true,
          total_price: true,
          status: true,
          payment_status: true,
          insurance: true,
          coupon_id: true,
          package_id: true,
          create_time: true
        })
        .get()
      
      if (!orderRes.data || orderRes.data.length === 0) {
        return {
          code: 404,
          message: '订单不存在'
        }
      }
      
      const order = orderRes.data[0]
      
      // 获取站点信息
      const depotRes = await db.collection('depot')
        .doc(order.depot_id)
        .field({
          name: true,
          address: true,
          contact: true
        })
        .get()
      
      // 获取格子信息
      const cellRes = await db.collection('locker_cell')
        .doc(order.cell_id)
        .field({
          cell_code: true,
          qr_code: true
        })
        .get()
      
      // 获取优惠券信息（如果使用）
      let coupon = null
      if (order.coupon_id) {
        const couponRes = await db.collection('coupon')
          .doc(order.coupon_id)
          .field({
            name: true,
            discount_type: true,
            value: true
          })
          .get()
        
        if (couponRes.data && couponRes.data.length > 0) {
          coupon = couponRes.data[0]
        }
      }
      
      // 组合数据
      const result = {
        ...order,
        depot: depotRes.data[0] || {},
        cell: cellRes.data[0] || {},
        coupon
      }
      
      return {
        code: 0,
        message: '获取订单详情成功',
        data: result
      }
    } catch (e) {
      console.error('获取订单详情失败:', e)
      return {
        code: 500,
        message: '获取订单详情失败',
        data: null
      }
    }
  }
}